package com.example.pei.ithinklearnt.view.activity;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.Toast;

import com.aurelhubert.ahbottomnavigation.AHBottomNavigation;
import com.aurelhubert.ahbottomnavigation.AHBottomNavigationAdapter;
import com.aurelhubert.ahbottomnavigation.AHBottomNavigationViewPager;
import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.baidu.autoupdatesdk.UICheckUpdateCallback;
import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.adapter.tabbarViewPageAdapter;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.event.RefreshEvent;
import com.example.pei.ithinklearnt.event.UnReadCountEvent;
import com.example.pei.ithinklearnt.utils.IMMLeaks;
import com.example.pei.ithinklearnt.utils.MyUtils;
import com.example.pei.ithinklearnt.view.base.BaseActivity;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.qiantao.coordinatormenu.CoordinatorMenu;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.core.ConnectionStatus;
import cn.bmob.newim.listener.ConnectListener;
import cn.bmob.newim.listener.ConnectStatusChangeListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

import static com.example.pei.ithinklearnt.AppApplication.getCurrentUser;
import static com.example.pei.ithinklearnt.AppApplication.setAHBottomNavigation;
import static com.example.pei.ithinklearnt.utils.ImageLoaderUtil.displayImage;
import static com.example.pei.ithinklearnt.utils.ImageLoaderUtil.getPhotoImageOption;
import static com.example.pei.ithinklearnt.utils.MyUtils.AppRunTime;

public class MainActivity extends BaseActivity {

    private AHBottomNavigation bottomNavigation;

    private final int RC_ACHIEVE_ALL_PERM=13;

    private KProgressHUD progressHUD;

    @BindView(R.id.iv_background)
    ImageView ivBackground;

    @BindView(R.id.coormain)
    CoordinatorMenu coordinatorMenu;

    private UserInfo user = AppApplication.getCurrentUser();
    private ConnectListener connectListener= new ConnectListener() {
        @Override
        public void done(String uid, BmobException e) {
            if (e == null) {
                user = AppApplication.getCurrentUser();
                //服务器连接成功就发送一个更新事件，同步更新会话及主页的小红点
                EventBus.getDefault().post(new RefreshEvent());
                //TODO 会话：2.7、更新用户资料，用于在会话页面、聊天页面以及个人信息页面显示
                BmobIM.getInstance().
                        updateUserInfo(new BmobIMUserInfo(user.getObjectId(),
                                user.getNickName(), user.getHeadFileUrl()));
            } else {
                // toast(e.getMessage());
                toast("网络不佳??");
            }
        }
    };

    public void openMenu(){
        coordinatorMenu.openMenu();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initUi();
        initCoverImage();


        //TODO 连接：3.1、登录成功、注册成功或处于登录状态重新打开应用后执行连接IM服务器的操作
        //判断用户是否登录，并且连接状态不是已连接，则进行连接操作
        if (!TextUtils.isEmpty(user.getObjectId()) && BmobIM.getInstance().getCurrentStatus().getCode() != ConnectionStatus.CONNECTED.getCode()) {
            BmobIM.connect(user.getObjectId(), connectListener);
            //TODO 连接：3.3、监听连接状态，可通过BmobIM.getInstance().getCurrentStatus()来获取当前的长连接状态
            BmobIM.getInstance().setOnConnectStatusChangeListener(new ConnectStatusChangeListener() {
                @Override
                public void onChange(ConnectionStatus status) {
                    if (!TextUtils.isEmpty(user.getObjectId()) && BmobIM.getInstance().getCurrentStatus().getCode() != ConnectionStatus.CONNECTED.getCode()) {
                        BmobIM.connect(user.getObjectId(),connectListener );
                    }
                }
            });
        }
        //解决leancanary提示InputMethodManager内存泄露的问题
        IMMLeaks.fixFocusedViewLeak(getApplication());

        //如果是第一次运行程序，则尝试获取所有所需的权限
        if(AppRunTime()==1){
            requestAllPermissions();
        }

    }

    @AfterPermissionGranted(RC_ACHIEVE_ALL_PERM)
    private void requestAllPermissions(){
        String[] perms = {
                // 把想要申请的权限放进这里就行，注意用逗号隔开
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.RECORD_AUDIO
        };
        if (EasyPermissions.hasPermissions(this, perms)) {

        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "为了更好的体验，请开启以下权限",
                    RC_ACHIEVE_ALL_PERM, perms);
        }
    }




    private void initUi() {
        bottomNavigation =  findViewById(R.id.bottom_navigation);
        final AHBottomNavigationViewPager viewPager = findViewById(R.id.view_pager);
        int[] tabColors = getApplicationContext().getResources().getIntArray(R.array.tab_colors);
        AHBottomNavigationAdapter navigationAdapter = new AHBottomNavigationAdapter(this, R.menu.bottom_navigation_menu_5);
        navigationAdapter.setupWithBottomNavigation(bottomNavigation, tabColors);
        //bottomNavigation.setColored(true);

        //设置底部导航的背景颜色
        bottomNavigation.setDefaultBackgroundColor(Color.parseColor("#ffffff"));
        //被选中的颜色
        bottomNavigation.setAccentColor(Color.parseColor("#309ab2"));
        //没有被选中的颜色
        bottomNavigation.setInactiveColor(Color.parseColor("#858994"));

        bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);


        bottomNavigation.setBehaviorTranslationEnabled(false);

        setAHBottomNavigation(bottomNavigation);////，，，
        bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
            @Override
            public boolean onTabSelected(int position, boolean wasSelected) {
            viewPager.setCurrentItem(position, false);
            return true;
            }
        });

        viewPager.setOffscreenPageLimit(4);
        tabbarViewPageAdapter adapter = new tabbarViewPageAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);



    }



    long exitTime=0;// 退出时间
    /** 捕捉按下返回键操作 */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO 按两次返回键退出应用程序
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            // 判断间隔时间 大于2秒就退出应用
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                // 应用名
             //  String applicationName = getResources().getString(R.string.app_name);
                String msg = "再按一次返回键退出";
                //String msg1 = "再按一次返回键回到桌面";
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                // 计算两次返回键按下的时间差
                exitTime = System.currentTimeMillis();
            } else {
                // 关闭应用程序
                finish();
                // 返回桌面操作
                // Intent home = new Intent(Intent.ACTION_MAIN);
                // home.addCategory(Intent.CATEGORY_HOME);
                // startActivity(home);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**注册自更新总未读数量事件
     * @param event
     */
    @Subscribe
    public void onEventMainThread(UnReadCountEvent event){
        bottomNavigation.setNotification((int)event.count, 1);
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    /**
     * 初始化封面
     */
    public void initCoverImage() {

        //调整图片的大小
        float density = this.getResources().getDisplayMetrics().density;  //屏幕密度
        float mScreenWidth = this.getResources().getDisplayMetrics().widthPixels;//屏幕宽度 pix
        float mMenuWidth = mScreenWidth - (int)(64.0F * density + 0.5F);   //侧滑栏宽度 pix

        float pictureHeight= density*180;  //图片高度  pix

        float adjustHeight=mMenuWidth*pictureHeight/mScreenWidth;  //应该调整的高度 pix

        ivBackground.getLayoutParams().height = (int)adjustHeight;
        ivBackground.getLayoutParams().width = (int)mMenuWidth;

        //设置bitmap
        String coverPath;
        coverPath=getExternalCacheDir()+"/cover-"+getCurrentUser().getUsername()+".jpg";
        File coverfile=new File(coverPath);
        if(!coverfile.exists()){
            //如果本地不存在文件 则加载网络图片
            String url=getCurrentUser().getCoverFileUrl();
            if(url==null||url.equals("")){
                ivBackground.setImageResource(R.drawable.banner_default);
            }else{
                displayImage(this, ivBackground, url, getPhotoImageOption());
            }
        }else {
            //本地存在封面文件，直接使用
            Bitmap bitmap = BitmapFactory.decodeFile(coverPath);
            ivBackground.setImageBitmap(bitmap);;
        }
    }

    /**
     * 退出登录
     */
    @OnClick(R.id.btn_exit)
    void logout(){
        BmobUser.logOut();   //清除缓存用户对象
        //回到登录界面
        Intent intent=new Intent(MainActivity.this, Login_Activity.class);
        startActivity(intent);
    }

    /**
     * 修改密码
     */
    @OnClick(R.id.btn_modpass)
    void changePasswd(){
        //忘记密码界面
        if(AppApplication.getCurrentUser().getMobilePhoneNumber()==null||AppApplication.getCurrentUser().getMobilePhoneNumber().equals(""))
        {
            toast("您不需要修改密码哦~~~");
            return;
        }
        Intent intent=new Intent(MainActivity.this, ForgetPassWordActivity.class);
        startActivity(intent);
    }

    //修改用户信息
    @OnClick(R.id.btn_modify)
    void updataUserInfo(){
        Intent intent=new Intent(this,RegisterTwoActivity.class);
        intent.putExtra("isModify","yes");
        startActivity(intent);
    }

    //关于我们
    @OnClick(R.id.btn_about)
    void aboutUs(){
        toast("敬请期待 ￣▽￣");
    }
    //用户反馈
    @OnClick(R.id.btn_feedback)
    void feedback(){
        Intent intent=new Intent(this,FeedBackActivity.class);
        startActivity(intent);
    }
    //版本更新
    @OnClick(R.id.btn_update)
    void update(){
        progressHUD = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setDimAmount(0.4f)
                .setLabel("正在检查新版本...")
                .setCornerRadius(10)
                .show();
        BDAutoUpdateSDK.uiUpdateAction(this, new MyUICheckUpdateCallback());
    }
    private class MyUICheckUpdateCallback implements UICheckUpdateCallback {

        @Override
        public void onNoUpdateFound() {
            toast("此版本已是最新.");
            progressHUD.dismiss();
        }

        @Override
        public void onCheckComplete() {
            progressHUD.dismiss();
        }

    }
}
